package com.ph.myblog.services;
 
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.ph.myblog.dao.HibernateUtil; 
import com.ph.myblog.entity.Articletype;

public class ArticleTypeServices {

	private Session session;

	public ArticleTypeServices() {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
	}

	public void add(Articletype type) throws Exception {

		try {
			session.beginTransaction();
			session.save(type);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public int update(Articletype type) throws Exception {
		
		try {
			session.beginTransaction();
			Query q = session
					.createQuery("update Articletype set title = ? ,description=? where id = ? ");
			q.setParameter(0, type.getTitle());
			q.setParameter(1, type.getDescription());
			q.setParameter(2, type.getId());
			int size = q.executeUpdate();
			session.getTransaction().commit();
			return size;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public int delete(Articletype type) throws Exception {

		int size = this.delete(type.getId());
		return size;
	}

	public int delete(int id) throws Exception {

		session.beginTransaction();
		Query q = session.createQuery("delete from Articletype where id = ? ");
		q.setParameter(0, id);
		int size = q.executeUpdate();
		session.getTransaction().commit();
		return size;
	}

	public List<Articletype> list() throws Exception {

		try {
			session.beginTransaction();
			List<Articletype> list = session.createQuery("from Articletype at order by at.id DESC ").list();
			session.getTransaction().commit(); 
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public Articletype loadTypeById(Articletype type) throws Exception {

		session.beginTransaction();
		Query q = session.createQuery("from Articletype at where at.id = ? ");
		q.setParameter(0, type.getId());
		List<Articletype> list = q.list();
		session.getTransaction().commit();
		return list.get(0);
	}
}
